package com.cdsxt.util;

import java.util.HashMap;
import java.util.Map;


/**
 * 
 */
public class MapPlus<KeyType, ValType> extends HashMap<KeyType, ValType> {
	
	public static void main(String[] args) {
		MapPlus<String, Object> map=new MapPlus<String, Object>();
		map.putSelf("name", "刘德华").putSelf("age", "18").putSelf("sex", "男");
		
		Map<Object, Object> map2= map.toMap();
		Map<String, String> map3= map.toMap();
		
		System.out.println(map);
		System.out.println(map2);
		System.out.println(map3);
		
	}
	
	
	//添加键值对-并返回自己
	public MapPlus<KeyType, ValType> putSelf(KeyType key, ValType val){
		/**
		 * 利用组合的map功能
		 */
		this.put(key, val);
		/**
		 * 返回自己实现链式编程
		 */
		return this;
	}
	
	//获取值：不需要类型转换
	
	public <AnyType> AnyType getValue(String key) {
		return (AnyType) this.get(key);
	}
	
	
	
	/**
	 * 转换其他类型 map
	 */
	public  <AnyType> AnyType toMap(){
		return (AnyType) this;
	}  
	
	/**
	 * 构建copy的map数据
	 */
	public static MapPlus build() {
		MapPlus<Object,Object> mapPlus = new MapPlus<>();
		return mapPlus;
	}
	/**
	 * 构建copy的map数据
	 */
	public static MapPlus build(Map<?, ?> map) {
		MapPlus<Object,Object> mapPlus = new MapPlus<>();
		mapPlus.putAll(map);
		return mapPlus;
	}
	/**
	 * 初始化map数据并返回map的过程
	 * --》模拟bean对象的构造器
	 * keyVals:装键值对的数据
	 * 格式；
	 * key,val,key,val ....
	 */
	public static MapPlus build(Object ...keyVals){
		MapPlus<Object, Object> map=new MapPlus<>();
		for (int i = 0; i < keyVals.length; i+=2) {
			//取出key
			Object key=keyVals[i];
			Object val=keyVals[i+1];
			//放入map
			map.put(key, val);
		}
		return map;
	}
	
	/**
	 * 查看字符串数据
	 */
	@Override
	public String toString() {
		StringBuilder sb=new StringBuilder();
		for (Map.Entry<KeyType,ValType> entry : this.entrySet()) {
			sb.append("key:"+entry.getKey());
			sb.append(" val:"+entry.getValue());
			sb.append("\n");
		}
		return sb.toString();
	}
}
